﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.ApplicationBlock;
using System.Configuration;
using DotNetOpenAuth.OAuth;
using System.Web.Security;
using DotNetOpenAuth.Messaging;

namespace SSOExample
{
    public partial class SignInWithTwitter : System.Web.UI.Page
    {
        private string AccessToken
        {
            get { return (string)Session["TwitterAccessToken"]; }
            set { Session["TwitterAccessToken"] = value; }
        }

        private InMemoryTokenManager TokenManager
        {
            get
            {
                var tokenManager = (InMemoryTokenManager)Application["TwitterTokenManager"];
                if (tokenManager == null)
                {
                    string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
                    string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
                    if (!string.IsNullOrEmpty(consumerKey))
                    {
                        tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
                        Application["TwitterTokenManager"] = tokenManager;
                    }
                }

                return tokenManager;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.TokenManager != null)
            {
                if (!base.IsPostBack)
                {
                    var twitter = new WebConsumer(TwitterConsumer.SignInWithTwitterServiceDescription, this.TokenManager);

                    // Is Twitter calling back with authorization?
                    var accessTokenResponse = twitter.ProcessUserAuthorization();
                    if (accessTokenResponse != null)
                    {
                        this.AccessToken = accessTokenResponse.AccessToken;

                        // In a real app, the Twitter username would likely be used
                        // to log the user into the application.

                        string screenName = accessTokenResponse.ExtraData["screen_name"];
                        int userId = Int32.Parse(accessTokenResponse.ExtraData["user_id"]);

                        FormsAuthentication.RedirectFromLoginPage(screenName, false);
                        base.Response.Redirect(FormsAuthentication.DefaultUrl);
                    }
                    else if (this.AccessToken == null)
                    {
                        // If we don't yet have access, immediately request it.
                        var redirectParameters = new Dictionary<string, string>();

                        Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_");
                        var request = twitter.PrepareRequestUserAuthorization(callback, null, redirectParameters);

                        twitter.Channel.PrepareResponse(request).Send();
                    }
                    else
                    {
                        base.Response.Redirect(FormsAuthentication.DefaultUrl);
                    }
                }
            }
        }
    }
}
